<template>
    <div id="google" class="googleMap"></div>
</template>

<script>
    export default {
        data () {
            return {
                map: null,
                mapMakers: [], // 保存标记对象
                infoWindows: [],  // 保存信息窗口对象
                toHistory: {
                    from: 'google'
                },
                timer: null // 保存刷新定时器
            }
        },
        methods: {
            // 获取点击地址
            getAddress (e, _this) {
                let geocoder = new google.maps.Geocoder()
                geocoder.geocode({location: e.latLng}, function geoResults (results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        _this.$emit('sendAddrMsg', results[0].formatted_address ? results[0].formatted_address : '')
                    }
                })
            },
            getEquip (data) {
                let json = $.extend(true, {}, data)
                if (this.infoWindows.length > 0) {
                    this.infoWindows.forEach(function (value, key) { // 确保每次只生成一个infowindow
                        value.close()
                    })
                }
                this.infoWindows.length = 0
                this.createMark(json)
            },
            // 点击客户时，得到多个设备，显示maker调用此函数
            getEquips (equips) {
                this.mapMakers.forEach((item) => {
                    item.setMap(null)
                })
                this.clearTimer()
                this.showEquipName(false) // 设置设备名称不可见
                if (equips.equips) {
                    equips.equips.forEach((item) => {
                        this.getEquip(item)
                    })
                }
            },
            // 实时跟踪
            trackInTime (equip) {
                this.setTimer(equip)
                if (equip.imei === undefined) {
                    return
                }
                this.$ajax
                    .equip
                    .queryEquipCoordinate(equip.imei)
                    .then((res) => {
                        let result = res.data
                        if (result.code === 200) {
                            if (result.result.lat === undefined) {
                                return // 无坐标信息
                            }
                            let coordinate = wgs84togcj02(result.result.lng * 1, result.result.lat * 1)
                            let obj = JSON.parse(JSON.stringify(result.result))
                            obj.lng = coordinate[0]
                            obj.lat = coordinate[1]
                            this.map.panTo({lng: obj.lng, lat: obj.lat})
                            /**
                             * 此处只是每次都会讲屏幕移至新的坐标点，但是在新位置却未生成新的marker
                             * 注意：生成新marker后，上一个marker需去掉
                             * 调用createMark(obj)方法
                             */
                        } else if (result.code === 408) {
                            this.$store.commit('showAlert', {error: this.$msgDictionary.loginGetaway})
                            let timer = setTimeout(() => {
                                clearTimeout(timer)
                                $('#msgModal').modal('hide')
                                this.$router.push({path: '/login'})
                            }, 2000)
                        } else {
                            this.$store.commit('showAlert', {error: result.msg})
                        }
                    }, () => {
                        this.$store.commit('showAlert', {error: this.$msgDictionary.serviceException})
                    })
            },
            historyTrail (imei) {
                this.clearTimer()
                this.toHistory.imei = imei
                this.$router.push({path: '/history', query: {key: this.toHistory}})
            },
            equipInfo (imei) {
                this.$emit('showEquipInfo', imei)
            },
            createMark (val) {   //调用此函数创建标记点
                let src = val.online ? 'static/images/icon_1_online.png' : 'static/images/icon_1_offline.png'
                if (val.lat === undefined) {
                    return
                }
                val.lat = Number(val.lat)
                val.lng = Number(val.lng)
                let coordinate = wgs84togcj02(val.lng, val.lat)
                val.lng = coordinate[0]
                val.lat = coordinate[1]
                let marker = new google.maps.Marker({
                    position: {lat: val.lat, lng: val.lng},
                    icon: src,
                    animation: google.maps.Animation.DROP,
                    map: this.map
                })
                let btnCss = 'height: 26px;border-radius: 13px;padding: 0 8px;border: 0;' +
                    'outline: none;font-size: 12px;color: #17D29C;background: #fff;border: 1px solid #17D29C; margin: 10px 0'
                let footCss = 'color: #17D29C;font-weight: bold;padding: 0 5px;color: #999'
                let html = `
                    <div style="width: 100%;height: 178px">
                        <div style="width: 60%;float: left;padding: 8px 0 0 20px">
                            <p>${val.name}</p>
                            <p>${val.imei}</p>
                            <p>${val.online ? '在线' : '离线'}</p>
                            <p>电量${val.online ? val.electricity + '%' : ''}</p>
                            <p>定位于<br>${val.locationTime}</p>
                        </div>
                        <div style="width: 40%;float: right;">
                            <ul style="list-style: none;padding: 0;margin: 0">
                                <li><button type="button" style="${btnCss}" id="trackInTime">实时跟踪</button></li>
                                <li><button type="button" style="${btnCss}" id="historyTrail">历史轨迹</button></li>
                                <li><button type="button" style="${btnCss}" id="equipInfo">设备信息</button></li>
                            </ul>
                        </div>
                    </div>
                    <p style="text-align: left;width: 250px;color: #999;padding-left: 17px">
                        <span style="${footCss}">|</span>
                        撤防
                        <span style="${footCss}">|</span>
                        车门关
                        <span style="${footCss}">|</span>
                        主电断开
                        <span style="${footCss}">|</span>
                    </p>
                `
                let objE = document.createElement('div')
                objE.innerHTML = html
                let infoWindow = new google.maps.InfoWindow({
                    content: objE
                })
                infoWindow.content.addEventListener('click', (e) => {
                    switch (e.target.id) {
                        case 'trackInTime':
                            this.trackInTime(val)
                            break
                        case 'historyTrail':
                            this.historyTrail(val.imei)
                            break
                        case 'equipInfo':
                            this.equipInfo(val)
                            break
                        default:
                            return
                    }
                })
                this.infoWindows.push(infoWindow)
                this.mapMakers.push(marker)
                let myOptions = {
                    content: val.name,
                    disableAutoPan: false,
                    maxWidth: 0,
                    pixelOffset: new google.maps.Size(30, -42),
                    zIndex: null,
                    boxStyle: {
                        opacity: 1,
                        width: 'auto',
                        borderRight: '1px solid #344045',
                        padding: '8px 10px',
                        color: '#344045',
                        fontSize: '12px',
                        background: 'transparent url(\'static/images/device_bg_small.png\') no-repeat'
                    },
                    closeBoxMargin: '10px 2px 2px 2px',
                    closeBoxURL: '',
                    infoBoxClearance: new google.maps.Size(1, 1),
                    isHidden: false,
                    pane: 'floatPane',
                    enableEventPropagation: false
                }
                let ib = new InfoBox(myOptions)
                ib.open(this.map, marker) //显示名字
                infoWindow.open(this.map, marker)
                marker.addListener('click', (e) => {
                    $('.gm-style-iw').parent().css('display', 'none')
                    infoWindow.open(this.map, marker)
                })
            },
            showEquipName (bool) {
                $('.infoBox').css('display', bool ? 'block' : 'none')
            },
            createRefresh (time) {
                let div = document.getElementById('refreshDiv')
                if (div) {
                    div.parentNode.removeChild(div)
                }
                let controlDiv = document.createElement('div')
                controlDiv.id = 'refreshDiv'
                let p = document.createElement('p')
                let span = document.createElement('span')
                span.id = 'refreshTime'
                span.style.color = '#f00'
                span.innerHTML = time
                p.appendChild(span)
                p.style.background = '#fff'
                p.style.padding = '5px'
                p.style.marginTop = '20px'
                p.innerHTML = p.innerHTML + ' 秒后刷新!'
                controlDiv.appendChild(p)
                this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(controlDiv)
            },
            // 每隔15秒刷新一次
            setTimer (data) {
                let time = 15
                this.clearTimer()
                this.createRefresh(time)
                this.timer = setInterval(() => {
                    time--
                    let div = document.getElementById('refreshDiv')
                    if (div) {
                        document.getElementById('refreshTime').innerHTML = time
                    } else {
                        this.clearTimer()
                    }
                    if (time < 0) {
                        this.clearTimer()
                        if (div && div.parentNode) {
                            div.parentNode.removeChild(div)
                        }
                        this.trackInTime(data)
                    }
                }, 1000)
            },
            clearTimer () {
                clearInterval(this.timer)
                let div = document.getElementById('refreshDiv')
                if (div) {
                    div.parentNode.removeChild(div)
                }
            }
        },
        destroyed () {
            this.clearTimer()
        },
        mounted () {
            let point = {lat: 22.560118, lng: 113.956033} //中心点
            this.map = new google.maps.Map(document.getElementById('google'), {//创建谷歌地图
                center: point,                       //地图的中心点
                zoom: 15,               　　　　　　　　　　  //地图缩放比例
                mapTypeId: google.maps.MapTypeId.ROADMAP,   //指定地图展示类型：卫星图像、普通道路
                scrollwheel: true,          　　　　　　　　　 //是否允许滚轮滑动进行缩放
                zoomControlOptions: {                      //缩放控件
                    position: google.maps.ControlPosition.TOP_LEFT  //设置位置 左上
                },
                //地图类型控件
                mapTypeControlOptions: {
                    position: google.maps.ControlPosition.TOP_RIGHT
                },
                //街景小人控件
                streetViewControlOptions: {
                    position: google.maps.ControlPosition.TOP_LEFT
                },
                // 启用缩放
                scaleControl: true,
            })
            let _this = this
            // 地图点击事件
            this.map.addListener('click', function (e) {
                _this.getAddress(e, _this)
            })
        },
    }
</script>

<style scoped>
    /* 地图引入 */
    html, body, .googleMap {
        width: 100%;
        height: 7.9rem;
        overflow: hidden;
        margin: 0;
    }

    .googleMap {
        width: 100%;
        height: 93.6%;
    }

    .infoWindow {
        border: 1px solid #f00;
        background: #f00;
    }

    ul {
        list-style: none;
    }
</style>
